import { Storage } from 'wepyk-api/lib/storage/index'

let storage
let cache = []

const STORAGE_NAME = 'searchhistory'

export function push(v, useStore = false) {
  if (useStore) {
    cache = getAll()
  }
  cache.push(v)
  storage.set(STORAGE_NAME, cache)
}

export function pop(delta = 1) {
  popStore(delta)
}

export function save(c) {
  cache = c
  storage.set(STORAGE_NAME, cache)
}

export function popStore(delta = 1, useStore = false) {
  if (useStore) {
    cache = getAll()
  }
  cache = cache.slice(0, cache.length - delta)
  storage.set(STORAGE_NAME, cache)
}

export function getAll(useStore = true) {
  let res = JSON.parse(JSON.stringify(cache))
  if (useStore) {
    res = storage.get(STORAGE_NAME)
  }
  if (!Array.isArray(res)) {
    return []
  }
  return res
}


export function clear() {
  cache = []
  storage.set(STORAGE_NAME, cache)
}

export function init() {
  storage = new Storage(wx)
  storage.set(STORAGE_NAME, cache)
}
